<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 网页授权：PC网站，手机站
// +----------------------------------------------------------------------
namespace app\sso\http\web;

use Inphp\Core\Object\Message;
use Inphp\Core\Util\Str;

class auth
{
    /**
     * 网页授权入口
     */
    public function index()
    {
        $plugin = GET("plugin");
        $plugin = !empty($plugin) ? Str::trim($plugin) : null;
        if (empty($plugin)) {
            //插件不存在
            showErrorPage("缺少授权插件名称参数");
            return;
        }
        //检测插件是否存在
        $controller = join("\\", ['app\sso\thirdParty', $plugin, 'auth']);
        if (!class_exists($controller)) {
            showErrorPage("无法处理该授权请求", "没有该类型的授权插件");
            return;
        }
        //触发方法处理
        if (method_exists($controller, "process")) {
            $result = $controller::process();
            if ($result instanceof Message) {
                if ($result->error === 301) {
                    redirect($result->message);
                    return;
                }
                if ($result->error === 0) {
                    //根据重定向地址处理
                    $redirect = GET("redirect");
                    $redirect = !empty($redirect) ? $redirect : "/";
                    if (!empty($result->data) && is_array($result->data)) {
                        $query = [];
                        foreach ($result->data as $key => $value) {
                            $query[] = "{$key}={$value}";
                        }
                        $redirect .= (stripos($redirect, "?") > 0 ? "&" : "?").join("&", $query);
                    }
                    redirect($redirect);
                    return;
                }
                showErrorPage($result->message);
            }
        }
    }
}